<template>
  <div class="website-speed-test-tool">
    <div class="tool-header">
      <h1>网站速度测试</h1>
      <p>测试网站加载速度</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 测试主体 -->
        <el-col :span="16">
          <div class="test-section">
            <!-- 测试输入 -->
            <div class="test-input">
              <h3>网站速度测试</h3>
              <div class="input-group">
                <el-input
                  v-model="websiteUrl"
                  placeholder="请输入网站URL，如：https://www.example.com"
                  size="large"
                  @keyup.enter="startTest"
                >
                  <template #prepend>
                    <el-icon><Link /></el-icon>
                  </template>
                  <template #append>
                    <el-button @click="startTest" type="primary" :loading="isTesting" :disabled="!websiteUrl.trim()">
                      开始测试
                    </el-button>
                  </template>
                </el-input>
              </div>
              
              <div class="test-options">
                <div class="option-group">
                  <label>测试位置：</label>
                  <el-select v-model="testLocation" size="small">
                    <el-option label="北京" value="beijing" />
                    <el-option label="上海" value="shanghai" />
                    <el-option label="广州" value="guangzhou" />
                    <el-option label="深圳" value="shenzhen" />
                  </el-select>
                </div>
                <div class="option-group">
                  <label>测试次数：</label>
                  <el-select v-model="testRounds" size="small">
                    <el-option label="1次" :value="1" />
                    <el-option label="3次" :value="3" />
                    <el-option label="5次" :value="5" />
                  </el-select>
                </div>
              </div>
            </div>
            
            <!-- 测试进度 -->
            <div class="test-progress" v-if="isTesting">
              <h4>测试进度</h4>
              <el-progress :percentage="testProgress" :status="testProgress === 100 ? 'success' : ''" />
              <div class="progress-info">
                <span>{{ testStatus }}</span>
                <span>{{ testProgress }}%</span>
              </div>
            </div>
            
            <!-- 测试结果 -->
            <div class="test-result" v-if="testResult">
              <h3>测试结果</h3>
              <div class="result-summary">
                <div class="summary-item">
                  <div class="summary-label">总体评分</div>
                  <div class="summary-value" :class="getScoreClass(testResult.overallScore)">
                    {{ testResult.overallScore }}
                  </div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">加载时间</div>
                  <div class="summary-value">{{ testResult.loadTime }}s</div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">首屏时间</div>
                  <div class="summary-value">{{ testResult.firstScreenTime }}s</div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">完全加载</div>
                  <div class="summary-value">{{ testResult.fullLoadTime }}s</div>
                </div>
              </div>
              
              <div class="detailed-metrics">
                <h4>详细指标</h4>
                <div class="metrics-grid">
                  <div class="metric-item">
                    <div class="metric-label">DNS解析时间</div>
                    <div class="metric-value">{{ testResult.dnsTime }}ms</div>
                    <div class="metric-bar">
                      <div class="metric-fill" :style="{ width: getMetricWidth(testResult.dnsTime, 100) }"></div>
                    </div>
                  </div>
                  <div class="metric-item">
                    <div class="metric-label">TCP连接时间</div>
                    <div class="metric-value">{{ testResult.tcpTime }}ms</div>
                    <div class="metric-bar">
                      <div class="metric-fill" :style="{ width: getMetricWidth(testResult.tcpTime, 200) }"></div>
                    </div>
                  </div>
                  <div class="metric-item">
                    <div class="metric-label">SSL握手时间</div>
                    <div class="metric-value">{{ testResult.sslTime }}ms</div>
                    <div class="metric-bar">
                      <div class="metric-fill" :style="{ width: getMetricWidth(testResult.sslTime, 300) }"></div>
                    </div>
                  </div>
                  <div class="metric-item">
                    <div class="metric-label">首字节时间</div>
                    <div class="metric-value">{{ testResult.ttfb }}ms</div>
                    <div class="metric-bar">
                      <div class="metric-fill" :style="{ width: getMetricWidth(testResult.ttfb, 500) }"></div>
                    </div>
                  </div>
                  <div class="metric-item">
                    <div class="metric-label">DOM构建时间</div>
                    <div class="metric-value">{{ testResult.domTime }}ms</div>
                    <div class="metric-bar">
                      <div class="metric-fill" :style="{ width: getMetricWidth(testResult.domTime, 1000) }"></div>
                    </div>
                  </div>
                  <div class="metric-item">
                    <div class="metric-label">资源加载时间</div>
                    <div class="metric-value">{{ testResult.resourceTime }}ms</div>
                    <div class="metric-bar">
                      <div class="metric-fill" :style="{ width: getMetricWidth(testResult.resourceTime, 2000) }"></div>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="recommendations" v-if="testResult.recommendations.length > 0">
                <h4>优化建议</h4>
                <div class="recommendation-list">
                  <div 
                    v-for="(rec, index) in testResult.recommendations" 
                    :key="index"
                    class="recommendation-item"
                    :class="rec.type"
                  >
                    <div class="rec-icon">
                      <el-icon v-if="rec.type === 'critical'"><Warning /></el-icon>
                      <el-icon v-else-if="rec.type === 'warning'"><InfoFilled /></el-icon>
                      <el-icon v-else><Check /></el-icon>
                    </div>
                    <div class="rec-content">
                      <div class="rec-title">{{ rec.title }}</div>
                      <div class="rec-description">{{ rec.description }}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 测试历史 -->
            <div class="test-history">
              <h3>测试历史</h3>
              <div class="history-list">
                <div 
                  v-for="(item, index) in testHistory" 
                  :key="index"
                  class="history-item"
                  @click="loadFromHistory(item)"
                >
                  <div class="history-url">{{ item.url }}</div>
                  <div class="history-metrics">
                    <span class="history-score" :class="getScoreClass(item.score)">{{ item.score }}</span>
                    <span class="history-time">{{ item.loadTime }}s</span>
                    <span class="history-date">{{ item.date }}</span>
                  </div>
                </div>
                <div v-if="testHistory.length === 0" class="empty-history">
                  暂无测试历史
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 工具和说明 -->
        <el-col :span="8">
          <div class="tools-section">
            <div class="section-header">
              <h3>常用网站</h3>
            </div>
            
            <div class="common-websites">
              <div 
                v-for="site in commonWebsites" 
                :key="site.url"
                class="website-item"
                @click="setWebsite(site.url)"
              >
                <div class="website-icon">{{ site.icon }}</div>
                <div class="website-info">
                  <div class="website-name">{{ site.name }}</div>
                  <div class="website-url">{{ site.url }}</div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="help-section">
            <el-card>
              <template #header>
                <div class="card-header">
                  <span>使用说明</span>
                </div>
              </template>
              
              <div class="help-content">
                <h4>测试指标：</h4>
                <ul>
                  <li><strong>DNS解析时间：</strong> 域名解析耗时</li>
                  <li><strong>TCP连接时间：</strong> 建立连接耗时</li>
                  <li><strong>SSL握手时间：</strong> HTTPS握手耗时</li>
                  <li><strong>首字节时间：</strong> 服务器响应时间</li>
                  <li><strong>DOM构建时间：</strong> 页面结构构建耗时</li>
                  <li><strong>资源加载时间：</strong> 静态资源加载耗时</li>
                </ul>
                
                <h4>评分标准：</h4>
                <ul>
                  <li><strong>90-100：</strong> 优秀</li>
                  <li><strong>80-89：</strong> 良好</li>
                  <li><strong>70-79：</strong> 一般</li>
                  <li><strong>60-69：</strong> 较差</li>
                  <li><strong>0-59：</strong> 很差</li>
                </ul>
                
                <h4>注意事项：</h4>
                <div class="warning">
                  <p>⚠️ 测试结果受网络环境影响</p>
                  <p>⚠️ 建议多次测试取平均值</p>
                  <p>⚠️ 某些网站可能有访问限制</p>
                </div>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Link, Warning, InfoFilled, Check } from '@element-plus/icons-vue'

const websiteUrl = ref('')
const testLocation = ref('beijing')
const testRounds = ref(3)
const isTesting = ref(false)
const testProgress = ref(0)
const testStatus = ref('')
const testResult = ref(null)
const testHistory = ref([])

const commonWebsites = [
  { name: '百度', url: 'https://www.baidu.com', icon: '🔍' },
  { name: '腾讯', url: 'https://www.qq.com', icon: '🐧' },
  { name: '阿里巴巴', url: 'https://www.alibaba.com', icon: '🛒' },
  { name: '京东', url: 'https://www.jd.com', icon: '📦' },
  { name: '新浪', url: 'https://www.sina.com.cn', icon: '📰' },
  { name: '网易', url: 'https://www.163.com', icon: '🎵' }
]

const validateURL = (url) => {
  try {
    new URL(url)
    return true
  } catch {
    return false
  }
}

const startTest = async () => {
  if (!websiteUrl.value.trim()) {
    ElMessage.warning('请输入网站URL')
    return
  }
  
  let url = websiteUrl.value.trim()
  if (!url.startsWith('http://') && !url.startsWith('https://')) {
    url = 'https://' + url
  }
  
  if (!validateURL(url)) {
    ElMessage.error('请输入有效的网站URL')
    return
  }
  
  isTesting.value = true
  testProgress.value = 0
  testResult.value = null
  
  try {
    // 模拟测试过程
    const steps = [
      '正在连接服务器...',
      'DNS解析中...',
      '建立TCP连接...',
      'SSL握手...',
      '发送请求...',
      '接收响应...',
      '解析HTML...',
      '加载资源...',
      '计算指标...',
      '生成报告...'
    ]
    
    for (let i = 0; i < steps.length; i++) {
      testStatus.value = steps[i]
      testProgress.value = ((i + 1) / steps.length) * 100
      await new Promise(resolve => setTimeout(resolve, 300))
    }
    
    // 模拟测试结果
    const mockResult = {
      overallScore: Math.floor(Math.random() * 40) + 60, // 60-100
      loadTime: (Math.random() * 3 + 1).toFixed(2),
      firstScreenTime: (Math.random() * 2 + 0.5).toFixed(2),
      fullLoadTime: (Math.random() * 4 + 2).toFixed(2),
      dnsTime: Math.floor(Math.random() * 50 + 10),
      tcpTime: Math.floor(Math.random() * 100 + 20),
      sslTime: Math.floor(Math.random() * 150 + 30),
      ttfb: Math.floor(Math.random() * 200 + 50),
      domTime: Math.floor(Math.random() * 500 + 100),
      resourceTime: Math.floor(Math.random() * 1000 + 200),
      recommendations: [
        {
          type: 'critical',
          title: '启用Gzip压缩',
          description: '可以减少传输数据量，提高加载速度'
        },
        {
          type: 'warning',
          title: '优化图片资源',
          description: '建议使用WebP格式或压缩图片'
        },
        {
          type: 'success',
          title: 'CDN配置良好',
          description: '已正确配置CDN加速'
        }
      ]
    }
    
    testResult.value = mockResult
    
    // 添加到历史
    addToHistory(url, mockResult)
    
    ElMessage.success('测试完成')
    
  } catch (error) {
    ElMessage.error('测试失败：' + error.message)
  } finally {
    isTesting.value = false
  }
}

const getScoreClass = (score) => {
  if (score >= 90) return 'excellent'
  if (score >= 80) return 'good'
  if (score >= 70) return 'fair'
  if (score >= 60) return 'poor'
  return 'bad'
}

const getMetricWidth = (value, max) => {
  return Math.min((value / max) * 100, 100) + '%'
}

const addToHistory = (url, result) => {
  const historyItem = {
    url: url,
    score: result.overallScore,
    loadTime: result.loadTime,
    date: new Date().toLocaleString('zh-CN')
  }
  
  testHistory.value.unshift(historyItem)
  
  // 限制历史记录数量
  if (testHistory.value.length > 20) {
    testHistory.value = testHistory.value.slice(0, 20)
  }
}

const loadFromHistory = (item) => {
  websiteUrl.value = item.url
  ElMessage.success(`已加载：${item.url}`)
}

const setWebsite = (url) => {
  websiteUrl.value = url
  ElMessage.success(`已设置网站：${url}`)
}
</script>

<style scoped>
.website-speed-test-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.test-section,
.tools-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.test-input,
.test-progress,
.test-result,
.test-history {
  margin-bottom: 30px;
}

.test-input h3,
.test-result h3,
.test-history h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.3rem;
}

.input-group {
  margin-bottom: 15px;
}

.test-options {
  display: flex;
  gap: 20px;
}

.option-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.option-group label {
  font-weight: 500;
  color: #666;
}

.test-progress h4 {
  color: #333;
  margin-bottom: 15px;
  font-size: 1.1rem;
}

.progress-info {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
  color: #666;
}

.result-summary {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
  margin-bottom: 30px;
}

.summary-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  border: 1px solid #e9ecef;
}

.summary-label {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 8px;
}

.summary-value {
  font-size: 1.5rem;
  font-weight: bold;
}

.summary-value.excellent {
  color: #28a745;
}

.summary-value.good {
  color: #20c997;
}

.summary-value.fair {
  color: #ffc107;
}

.summary-value.poor {
  color: #fd7e14;
}

.summary-value.bad {
  color: #dc3545;
}

.detailed-metrics h4 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.1rem;
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.metric-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  border: 1px solid #e9ecef;
}

.metric-label {
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 8px;
}

.metric-value {
  font-size: 1.2rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.metric-bar {
  height: 6px;
  background: #e9ecef;
  border-radius: 3px;
  overflow: hidden;
}

.metric-fill {
  height: 100%;
  background: #667eea;
  transition: width 0.3s ease;
}

.recommendations h4 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.1rem;
}

.recommendation-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.recommendation-item {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.recommendation-item.critical {
  background: #f8d7da;
  border-color: #f5c6cb;
}

.recommendation-item.warning {
  background: #fff3cd;
  border-color: #ffeaa7;
}

.recommendation-item.success {
  background: #d4edda;
  border-color: #c3e6cb;
}

.rec-icon {
  color: #666;
  margin-top: 2px;
}

.recommendation-item.critical .rec-icon {
  color: #dc3545;
}

.recommendation-item.warning .rec-icon {
  color: #ffc107;
}

.recommendation-item.success .rec-icon {
  color: #28a745;
}

.rec-title {
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.rec-description {
  font-size: 0.9rem;
  color: #666;
}

.history-list {
  max-height: 300px;
  overflow-y: auto;
}

.history-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 10px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.history-item:hover {
  background: #e9ecef;
  transform: translateY(-1px);
}

.history-url {
  font-size: 1rem;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.history-metrics {
  display: flex;
  gap: 15px;
  align-items: center;
}

.history-score {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: bold;
}

.history-score.excellent {
  background: #d4edda;
  color: #28a745;
}

.history-score.good {
  background: #d1ecf1;
  color: #20c997;
}

.history-score.fair {
  background: #fff3cd;
  color: #ffc107;
}

.history-score.poor {
  background: #f8d7da;
  color: #fd7e14;
}

.history-score.bad {
  background: #f8d7da;
  color: #dc3545;
}

.history-time {
  font-size: 0.9rem;
  color: #666;
}

.history-date {
  font-size: 0.8rem;
  color: #999;
}

.empty-history {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-style: italic;
}

.section-header {
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.common-websites {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.website-item {
  display: flex;
  align-items: center;
  gap: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid #e9ecef;
}

.website-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
}

.website-icon {
  font-size: 1.5rem;
}

.website-name {
  font-size: 1rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 2px;
}

.website-url {
  font-size: 0.9rem;
  color: #666;
}

.help-section {
  margin-top: 20px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.help-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.help-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.help-content li {
  margin-bottom: 5px;
}

.warning {
  background: #fff3cd;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #ffc107;
  margin: 15px 0;
}

.warning p {
  margin: 5px 0;
  color: #856404;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .test-options {
    flex-direction: column;
    gap: 10px;
  }
  
  .result-summary {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .metrics-grid {
    grid-template-columns: 1fr;
  }
  
  .history-metrics {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}
</style>
